package com.loop.unclelend.ui.adapter

import android.graphics.Color
import android.text.Editable
import android.text.SpannableString
import android.text.Spanned
import android.text.TextWatcher
import android.text.style.ForegroundColorSpan
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.EditText
import androidx.recyclerview.widget.RecyclerView
import com.loop.unclelend.R
import com.loop.unclelend.utils.adapter.UncleRecyclerViewAdapter
import com.loop.unclelend.utils.adapter.UncleViewHolderHelper
import com.loop.unclelend.utils.event.UncleEventHelper
import com.loop.unclelend.utils.event.UncleEventType
import com.loop.unclelend.utils.helper.SharedHelper
import org.json.JSONObject

/**
 * UncleLend
 * @Author wwdeng
 * @CreateTime: 2024/9/12 13:54
 * @Annotation：认证流程步骤适配器
 */
class Adapter_Step_Common(recyclerView: RecyclerView?): UncleRecyclerViewAdapter<JSONObject>(recyclerView) {
    override fun getItemViewType(position: Int): Int {
        val model = getItem(position)
        when(model.optString("action")){
            "DATE_PICK" ->{//时间选择
                return R.layout.uncle_item_step_common_select
            }
            "GENDER_PICK" -> {//性别
                return R.layout.uncle_item_step_common_gender
            }
            "CONTACT_GROUP_PHONE" -> {//联系人电话
                return R.layout.uncle_item_step_common_mobile
            }
            "SELECT" -> {//选择
                return R.layout.uncle_item_step_common_select
            }
            else -> {//输入框
                return R.layout.uncle_item_step_common_input
            }
        }
    }

    override fun setItemChildListener(helper: UncleViewHolderHelper, viewType: Int) {
        helper.setItemChildClickListener(R.id.layout_select)//选择
        helper.setItemChildClickListener(R.id.img_mobile_book)//选择联系人
        helper.setItemChildClickListener(R.id.txt_mobile)
    }

    override fun fillData(helper: UncleViewHolderHelper, position: Int, model: JSONObject) {
        //名称
        val textTitle = helper.getTextView(R.id.txt_select_title)
        textTitle.text = findKeywordColor(Color.parseColor("#FFFF4D3E"),model.optString("title"),"*")

        when(model.optString("action")){
            "DATE_PICK",
            "SELECT" ->{//时间选择、选择
                showUncleStepItemSelectView(helper,position,model)
            }
            "CONTACT_GROUP_PHONE" -> {//联系人电话
                showUncleStepItemContactMobileView(helper,position,model)
            }
            "GENDER_PICK" -> {//性别
                showUncleStepItemSelectGenderView(helper,position,model)
            }
            else -> {//输入框
                showUncleStepItemInputView(helper,position,model)
            }
        }
    }

    /**
     * 输入框类型
     */
    private fun showUncleStepItemInputView(helper: UncleViewHolderHelper, position: Int, model: JSONObject){
        //提示语
        val editText = helper.getView<EditText>(R.id.edit_text)
        editText.setHint(model.optString("hint"))
        editText.setBackgroundResource(R.drawable.radius_fill_fff2f0f5_8)
        var showText = ""
        if (model.has("selectItem")){
            showText = model.optJSONObject("selectItem").optString("title")
        }
        editText.setText(showText)
        editText.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_DONE){
                editText.clearFocus()
                true
            }
            false
        }
        editText.setOnFocusChangeListener { v, hasFocus ->
            if (!hasFocus){
                UncleEventHelper.addUncleRequestEventAction(String.format(UncleEventType.FORM.UNCLE_FORM_STEP_INPUT_XX,model.optString("paramName")),editText.text.toString())
            }
        }

        editText.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }
            override fun afterTextChanged(s: Editable?) {
                val obj = JSONObject()
                obj.put("title",s.toString())
                obj.put("value",s.toString())
                model.put("selectItem",obj)
            }
        })
    }

    /**
     * 选择性别
     */
    private fun showUncleStepItemSelectGenderView(helper: UncleViewHolderHelper, position: Int, model: JSONObject){
        val txtGender1 = helper.getTextView(R.id.txt_gender1)
        txtGender1.setTextColor(Color.parseColor("#FF747378"))
        txtGender1.setBackgroundResource(R.drawable.radius_fill_fff2f0f5_8)

        val txtGender2 = helper.getTextView(R.id.txt_gender2)
        txtGender2.setTextColor(Color.parseColor("#FF747378"))
        txtGender2.setBackgroundResource(R.drawable.radius_fill_fff2f0f5_8)

        val values = model.optJSONArray("values")
        if (values != null){
            if (values.length() > 0){
                val item = values.optJSONObject(0)
                txtGender1.text = item.optString("title")
            }
            if (values.length() > 1){
                val item = values.optJSONObject(1)
                txtGender2.text = item.optString("title")
            }
        }

        //选中
        if (model.has("selectItem")){
            val selectValue = model.getJSONObject("selectItem")
            if (values != null){
                if (values.length() > 0){
                    val item = values.optJSONObject(0)
                    if (item.optString("title") == selectValue.optString("title")){
                        txtGender1.setTextColor(Color.parseColor("#FFFFFFFF"))
                        txtGender1.setBackgroundResource(R.drawable.radius_fill_ff7000ff_8)
                    }
                }
                if (values.length() > 1){
                    val item = values.optJSONObject(1)
                    if (item.optString("title") == selectValue.optString("title")){
                        txtGender2.setTextColor(Color.parseColor("#FFFFFFFF"))
                        txtGender2.setBackgroundResource(R.drawable.radius_fill_ff7000ff_8)
                    }
                }
            }
        }

        txtGender1.setOnClickListener {
            if (values != null) {
                val item = values.optJSONObject(0)
                model.put("selectItem", item)
                UncleEventHelper.addUncleRequestEventAction(String.format(UncleEventType.CLICK.UNCLE_CLICK_STEP_XX_SELECT,model.optString("paramName")),item.optString("title"))
            }
            notifyItemChanged(position)
        }

        txtGender2.setOnClickListener {
            if (values != null) {
                val item = values.optJSONObject(1)
                model.put("selectItem", item)
                UncleEventHelper.addUncleRequestEventAction(String.format(UncleEventType.CLICK.UNCLE_CLICK_STEP_XX_SELECT,model.optString("paramName")),item.optString("title"))
            }
            notifyItemChanged(position)
        }
    }

    /**
     * 选择类型
     */
    private fun showUncleStepItemSelectView(helper: UncleViewHolderHelper, position: Int, model: JSONObject){
        //提示语
        val hint = model.optString("hint")
        val textValue = helper.getTextView(R.id.txt_value)
        textValue.setHint(hint)
        if (model.has("selectItem")){
            textValue.text = model.getJSONObject("selectItem").optString("title")
        }
    }

    /**
     * 联系电话
     */
    private fun showUncleStepItemContactMobileView(helper: UncleViewHolderHelper, position: Int, model: JSONObject){
        //提示语
        val hint = model.optString("hint")
        val textMobile = helper.getTextView(R.id.txt_mobile)
        textMobile.setHint(hint)
        val editMobile = helper.getView<EditText>(R.id.edit_mobile)
        editMobile.setHint(hint)
        if (model.has("selectItem")){
            val showValue = model.getJSONObject("selectItem").optString("title")
            textMobile.text = showValue
            editMobile.setText(showValue)
        }
        editMobile.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_DONE){
                editMobile.clearFocus()
                true
            }
            false
        }
        editMobile.setOnFocusChangeListener { v, hasFocus ->
            if (!hasFocus){
                UncleEventHelper.addUncleRequestEventAction(String.format(UncleEventType.FORM.UNCLE_FORM_STEP_INPUT_XX,model.optString("paramName")),editMobile.text.toString())
            }
        }
        editMobile.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }
            override fun afterTextChanged(s: Editable?) {
                val obj = JSONObject()
                obj.put("title",s.toString())
                obj.put("value",s.toString())
                model.put("selectItem",obj)
            }
        })

        //是否是审核账号
        val isConfigAccount = SharedHelper.getUncleSPBoolean(SharedHelper.UNCLE_SPKEY.UNCLE_IS_CONFIG_ACCOUNT)
        if(isConfigAccount){//审核账号 - 允许输入或选择
            textMobile.visibility = View.GONE
            editMobile.visibility = View.VISIBLE
        } else {//非审核账号只能选择
            textMobile.visibility = View.VISIBLE
            editMobile.visibility = View.GONE
        }
    }

    private fun findKeywordColor(color: Int, text: String, key: String): SpannableString {
        val spString = SpannableString(text)
        if (!text.contains(key)){
            return spString
        }
        val start = text.indexOf(key)
        val end = start + key.length
        spString.setSpan(ForegroundColorSpan(color), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        return spString
    }
}